﻿using System;
using System.IO;
using Excel;

namespace OfficeToPDF
{
    public class WpsAdapter : IAdapter
    {
        public bool IsKillAllWpsProcess { get; set; } = false;
        public string SourcePath { get; set; }
        private string _appName { get; set; }
        private dynamic _wps { get; set; }
        public WpsAdapter(string sourcePath, bool isKillAllWpsProcess = false)
        {
            if (File.Exists(sourcePath))
            {
                this.IsKillAllWpsProcess = isKillAllWpsProcess;
                this.SourcePath = sourcePath;
                string extension = Path.GetExtension(sourcePath)?.ToLower();
                
                switch (extension)
                {
                    case ".xls":
                        _appName = "KET.Application";
                        break;
                    case ".xlsx":
                        _appName = "KET.Application";
                        break;
                    case ".ppt":
                        _appName = "KWPP.Application";
                        break;
                    case ".pptx":
                        _appName = "KWPP.Application";
                        break;
                    default:
                        _appName = "KWps.Application";
                        break;
                }
                Type type = Type.GetTypeFromProgID(_appName);
                if (type == null)
                {
                    _appName = "wps.Application";
                    type = Type.GetTypeFromProgID("wps.Application");
                }
                _wps = Activator.CreateInstance(type);
            }
            else
            {
                throw new Exception("WpsAdapter-找不到源文件！");
            }
        }

        public bool SaveToPdf(string targetPath = "")
        {
            if (string.IsNullOrEmpty(SourcePath))
            {
                throw new Exception("WpsAdapter-SaveToPdf-找不到源文件!");
            }
            
            SourcePath = Path.GetFullPath(SourcePath ?? throw new InvalidOperationException());
            
            if (string.IsNullOrEmpty(targetPath))
            {
                targetPath = Path.ChangeExtension(SourcePath, "pdf");
            }

           

            switch (_appName)
            {
                case "KET.Application":
                    XlsToPdf(targetPath);
                    break;
                case "KWPP.Application":
                    PptToPdf(targetPath);
                    break;
                default:
                    DocToPdf(targetPath);
                    break;
            }

            return true;
        }

        private string DocToPdf(string TargetPath = "")
        {
            try
            {
                _wps.DisplayAlerts = false;
                dynamic doc = _wps.Documents.Open(SourcePath, Visible: false);
                doc.ExportAsFixedFormat(TargetPath, Word.WdExportFormat.wdExportFormatPDF);
                doc.Close();
                doc = null;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                Dispose();
            }
            return TargetPath;
        }

        private string XlsToPdf(string TargetPath = "")
        {
            try
            {
                XlFixedFormatType targetType = XlFixedFormatType.xlTypePDF;
                object missing = Type.Missing;
                _wps.DisplayAlerts = false;
                dynamic doc = _wps.Application.Workbooks.Open(SourcePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                doc.ExportAsFixedFormat(targetType, TargetPath, XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
                doc.Close();
                doc = null;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                Dispose();
            }
            return TargetPath;
        }

        private string PptToPdf(string targetPath = "")
        {

            try
            {
                _wps.DisplayAlerts = false;
                dynamic doc = _wps.Presentations.Open(SourcePath, PowerPoint.MsoTriState.msoCTrue,
                    PowerPoint.MsoTriState.msoCTrue, PowerPoint.MsoTriState.msoCTrue);
                object missing = Type.Missing;
                doc.SaveAs(targetPath, PowerPoint.PpSaveAsFileType.ppSaveAsPDF, PowerPoint.MsoTriState.msoTrue);
                doc.Close();
                doc = null;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                Dispose();
            }
            return targetPath;
        }

        public void Dispose()
        {
            if (_wps != null)
            {
                _wps.Quit();
                _wps = null;
                if (this.IsKillAllWpsProcess)
                {
                    System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("wps");
                    foreach (System.Diagnostics.Process prtemp in process)
                    {
                        prtemp.Kill();
                    }
                }
            }
        }
    }
}